#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stropts.h>
#include <stdio.h>
#include <stdlib.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <linux/input.h>
#include <time.h>
#include "func_lcd.h"

static const int size = 800*480*4;
static int lcdfd = -1;
static lcd p = NULL;

lcd open_lcd(){
    lcdfd = open(LCD,O_RDWR);
    if(-1 == lcdfd){
        perror("open err");
        return NULL;
    }
    printf("open success!\n");

    p = (lcd)mmap(NULL,size,PROT_READ|PROT_WRITE,MAP_SHARED,lcdfd,0);
    if(MAP_FAILED == p){
        perror("映射内存失败!\n");
        return NULL;
    }
    printf("映射内存成功!\n");
    return p;
}

int show_bmp(int x, int y, const char* pathname){
    int bmpfd = open(pathname,O_RDONLY);
    if(-1 == bmpfd){
        printf("%s\n",pathname);
        perror("open err");
        return -1;
    }
    unsigned char info[54] = {0};
    read(bmpfd,info,sizeof(info));

   // printf("标示:%c %c\n",info[0],info[1]); //B M

    unsigned int size = (info[5]<<24) | (info[4]<<16) | (info[3]<<8) | (info[2]<<0);
    //printf("bmp文件大小:%d\n",size);

    unsigned int bmp_w = (info[21]<<24) | (info[20]<<16) | (info[19]<<8) |(info[18]<<0);
    unsigned int bmp_h = (info[25]<<24) | (info[24]<<16) | (info[23]<<8) |(info[22]<<0);
   // printf("宽:%d\t高:%d\n",bmp_w,bmp_h);


    unsigned char* bmpbuf = (unsigned char*)malloc(bmp_w*bmp_h*3);
    read(bmpfd,bmpbuf,bmp_w*bmp_h*3);

    unsigned int* lcdbuf = (unsigned int*)malloc(bmp_w*bmp_h*sizeof(unsigned int));
    for(int i = 0;i<bmp_h*bmp_w;i++){
        lcdbuf[i] = (bmpbuf[i*3+0]<<0)|(bmpbuf[i*3+1]<<8)|(bmpbuf[i*3+2]<<16)|(0x00<<24);
    }

    for(int j = 0; j < bmp_h; j ++){ // 行   480
        for(int i = 0; i < bmp_w; i++){ // 列
            p[(x+i) + (y+j)* 800] = lcdbuf[i + (bmp_h -1 -j)* bmp_w];            
        }
    }
 
    free(bmpbuf);
    free(lcdbuf);
    int ret = close(bmpfd);
    if(-1 == ret){
        perror("close err");
        return -1;
    }
}

int close_lcd(lcd p){
    int ret = munmap(p,size);
    if(-1 == ret){
        perror("解除映射失败!\n");
        return -1;
    }
    printf("解除映射成功\n");
    ret = close(lcdfd);
    if(-1 == ret){
        perror("关闭设备失败!\n");
        return -1;
    }
    printf("关闭设备成功!\n");
    return 0;
}

void get_xy(int* x,int* y){
    int tsfd = open(EVENT,O_RDONLY);
    if(-1 == tsfd){
        perror("open err");
        return ;
    }

    struct input_event ts;
    *x == -1;
    *y == -1;
    while(((*x)==-1) || ((*y)==-1)){
        //获取设备的时间信息
        int ret = read(tsfd,&ts,sizeof(ts));
        if(-1 == ret){
            perror("读取失败");
            break;
        }

        if(ts.type == EV_ABS){
            if(ts.code == ABS_X){
                *x = ts.value;
            }
            if(ts.code == ABS_Y){
                *y = ts.value;
            }
        }
        
    }
    close(tsfd); 
}
